package PHANVANVUONG.JSON.HOMEWORK.API_TO_OBJECT;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

@SuppressWarnings("unused")
public class Controllers {

	public AppInfo MappingApiToObject(String url) throws Exception{
		String urlJson= IOUtils.toString(new URL(url));
		JSONObject objSon = (JSONObject) JSONValue.parseWithException(urlJson);
		
		AppInfo objApp=new AppInfo();
		List<Description> lisDescription=new ArrayList<Description>();
		
		objApp.setAverageRating(Double.parseDouble((String) objSon.get("AverageRating")));
		objApp.setSizeApps((String) objSon.get("SizeApps"));
		objApp.setAppid((String) objSon.get("appid"));
		objApp.setCatagoryName((String) objSon.get("catagoryName"));
		objApp.setCatagoryid((String) objSon.get("catagoryid"));
		objApp.setDescription((String) objSon.get("description"));
		objApp.setDownloadCount(Integer.parseInt(""+objSon.get("downloadCount")));
		objApp.setDownloadUrl((String) objSon.get("downloadUrl"));
		objApp.setErrormessage((String) objSon.get("errormessage"));
		objApp.setIcon((String) objSon.get("icon"));
		objApp.setImageCode((String) objSon.get("imageCode"));
		objApp.setName((String) objSon.get("name"));
		objApp.setPrice((String) objSon.get("price"));
		objApp.setProviderName((String) objSon.get("providerName"));
		objApp.setProviderid((String) objSon.get("providerid"));
		objApp.setReturnCode((String) objSon.get("returnCode"));
		objApp.setScreen_height(Integer.parseInt(""+objSon.get("screen_height")));
		objApp.setScreen_width(Integer.parseInt(""+objSon.get("screen_width")));
		objApp.setTotalrecord((String) objSon.get("totalrecord"));
		objApp.setUrl_share((String) objSon.get("url_share"));
		objApp.setVertions((String) objSon.get("vertions"));
		objApp.setView_count(Integer.parseInt(""+objSon.get("view_count")));
		
		JSONArray objArray=(JSONArray) objSon.get("lisDescription");
		
		JSONObject objJSon=null;
		Description objDes=null;
		
		for(int i=0; i<objArray.size(); i++){
			objJSon=(JSONObject) objArray.get(i);
			objDes=new Description();
			objDes.setAppId((String) objJSon.get("appId"));
			objDes.setDes_Images_Id((String) objJSon.get("Des_Images_Id"));
			objDes.setImages_URL((String) objJSon.get("Images_URL"));
			objDes.setLinks((String) objSon.get("Links"));
			objDes.setHeight(Integer.parseInt(""+objJSon.get("Height")));
			objDes.setWidth(Integer.parseInt(""+objJSon.get("Width")));
			objDes.setStatus(Boolean.parseBoolean(""+ objJSon.get("Status")));
			
			lisDescription.add(objDes);
		}
		objApp.setLisDescription(lisDescription);
		
		
		return objApp;
	}
}
